package nju.bishe.weibo.data.db;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

/**
 * 处理用户信息缓冲入数据库的类
 * @author longwei.wu
 *
 */
public class UserInfoDatabase {

	 private static final String TAG = "DatabaseHelper";

	    private static final String DATABASE_NAME = "userinfo_db";
	    private static final int DATABASE_VERSION = 1;

	    private static UserInfoDatabase instance = null;
	    private UserInfoDatabaseHelper uiOpenHelper = null;
	    private Context uiContext = null;
	    
	    /**
	     * 进行SQLiteDatabase操作的帮助类
	     * @author wlw
	     *
	     */
	    private static class UserInfoDatabaseHelper extends SQLiteOpenHelper{
	    	
	    	public UserInfoDatabaseHelper(Context context, String name,
                CursorFactory factory, int version){
	    		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	    	}
	    	
	    	public UserInfoDatabaseHelper(Context context){
	    		this(context, DATABASE_NAME, null, DATABASE_VERSION);
	    	}

	    	/**
	    	 * 创建数据库，执行建表语句
	    	 */
			@Override
			public void onCreate(SQLiteDatabase db) {
				// TODO Auto-generated method stub
				 Log.i(TAG, "Create Database.");
				 db.execSQL(UserInfoTable.CREATE_TABLE);
				
			}
			
	        @Override
	        public synchronized void close() {
	            Log.i(TAG, "Close Database.");
	            super.close();
	        }

	        @Override
	        public void onOpen(SQLiteDatabase db) {
	            Log.i(TAG, "Open Database.");
	            super.onOpen(db);
	        }

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion,
					int newVersion) {
				// TODO Auto-generated method stub
				 Log.i(TAG, "Upgrade Database.");
				 db.execSQL("DROP TABLE IF EXISTS " + UserInfoTable.TABLE_NAME);
			}
	    	
	    }
	    
	    private UserInfoDatabase(Context context){
	    	uiContext = context;
	    	uiOpenHelper  = new UserInfoDatabaseHelper(uiContext);
	    }
	    /**
	     * 获得用户信息数据库类的单例方法
	     * @param context
	     * @return
	     * 		用户信息数据库类的实例
	     */
	    public static synchronized UserInfoDatabase getInstance(Context context){
	    	 if (null == instance) {
	             return new UserInfoDatabase(context);
	         }
	         return instance;
	    }
	    
	      public void close() {
	        if (null != instance) {
	            uiOpenHelper.close();
	            instance = null;
	        }
	      }
	      
	      /**
	       * 查看数据是否已保存用户数据
	       * @param userId
	       * @return
	       */
	      public boolean existsUser(String userId) {
	          SQLiteDatabase Db = uiOpenHelper.getReadableDatabase();
	          boolean result = false;

	          Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
	                  new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'",
	                  null, null, null, null);
	          Log.i("testesetesteste", String.valueOf(cursor.getCount()));
	          if (cursor != null && cursor.getCount() > 0) {
	              result = true;
	          }

	          cursor.close();
	          return result;
	      }
	      
	      /**
	       * 根据userid提取信息
	       * @param userId
	       * @return
	       */
	      public Cursor getUserInfoById(String userId){
	      	  SQLiteDatabase Db = uiOpenHelper.getReadableDatabase();

	            Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
	                    UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'",
	                    null, null, null, null);

	          return cursor;
	      }
	      
	      /**
	       * 新建用户
	       * 
	       * @param user
	       * @return the row ID of the newly inserted row, or -1 if an error occurred
	       */
	      public long createUserInfo(nju.bishe.weibo.data.User user) {
	          SQLiteDatabase mDb = uiOpenHelper.getWritableDatabase();

	          ContentValues initialValues = new ContentValues();
	          initialValues.put(UserInfoTable._ID, user.id);
	          initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
	          initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
	          initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
	          initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
	          initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
	          initialValues.put(UserInfoTable.FIELD_URL, user.url);
	          initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
	          initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
	          initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
	          initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
	          initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
	          initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
	          initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
	          
	          
	          long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, initialValues);
	          if (-1 == rowId) {
	              Log.e(TAG, "Cann't create Follower : " + user.id);
	          } else {
	              Log.i(TAG, "create create follower : " + user.id);
	          }
	          return rowId;
	      }
	      
	      /**
	       * 更新用户
	       * @param uid
	       * @param args
	       * @return
	       */
	      public boolean updateUser(String uid,ContentValues args){
	      	SQLiteDatabase db=uiOpenHelper.getWritableDatabase();
	      	return db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0;
	      }
}
